import type {FormField, PropsConfig} from '@/components/base/CommonForm/types'
import type {ApiConfig, SearchField, TableColumn, TableConfig} from '@/components/base/CommonTable/types'
import {checkUserDuplicate, createUser, deleteUser, disableUser, enableUser, getUserPage, updateUser} from '@/api/user'

// 自定义校验函数
const validateUsername = async (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error('请输入用户名'))
    return
  }
  if (value.length > 50) {
    callback(new Error('用户名长度不能超过50个字符'))
    return
  }
  // 新增时检查重复
  if (rule.isEdit === false) {
    try {
      const result = await checkUserDuplicate({ username: value })
      if (result) {
        callback(new Error('用户名已存在'))
        return
      }
    } catch (error) {
      console.error('用户名重复检查失败:', error)
    }
  }
  callback()
}

const validateEmail = async (rule: any, value: any, callback: any) => {
  if (!value) {
    callback()
    return
  }
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
  if (!emailRegex.test(value)) {
    callback(new Error('请输入正确的邮箱格式'))
    return
  }
  // 新增时检查重复
  if (rule.isEdit === false) {
    try {
      const result = await checkUserDuplicate({ email: value })
      if (result) {
        callback(new Error('邮箱已存在'))
        return
      }
    } catch (error) {
      console.error('邮箱重复检查失败:', error)
    }
  }
  callback()
}

const validatemobile = async (rule: any, value: any, callback: any) => {
  if (!value) {
    callback()
    return
  }
  const mobileRegex = /^1[3-9]\d{9}$/
  if (!mobileRegex.test(value)) {
    callback(new Error('请输入正确的手机号'))
    return
  }
  // 新增时检查重复
  if (rule.isEdit === false) {
    try {
      const result = await checkUserDuplicate({ mobile: value })
      if (result) {
        callback(new Error('手机号已存在'))
        return
      }
    } catch (error) {
      console.error('手机号重复检查失败:', error)
    }
  }
  callback()
}

// 表单字段配置
export const getFormFields = (isEdit: boolean = false): FormField[] => {
  return [
    {
      prop: 'username',
      label: '用户名',
      type: 'input',
      required: true,
      maxlength: 50,
      showWordLimit: true,
      rules: [
        { validator: (rule, value, callback) => validateUsername({...rule, isEdit}, value, callback), trigger: 'blur' }
      ]
    },
    // 新增时的密码字段
    ...(isEdit ? [] : [
      {
        prop: 'password',
        label: '密码',
        type: 'password',
        required: true,
        maxlength: 50,
        rules: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
        ]
      },
      {
        prop: 'confirmPassword',
        label: '确认密码',
        type: 'password',
        required: true,
        rules: [
          { required: true, message: '请再次输入密码', trigger: 'blur' }
        ]
      }
    ]),
    {
      prop: 'nickname',
      label: '昵称',
      type: 'input',
      maxlength: 50,
      showWordLimit: true
    },
    {
      prop: 'email',
      label: '邮箱',
      type: 'input',
      rules: [
        { validator: (rule, value, callback) => validateEmail({...rule, isEdit}, value, callback), trigger: 'blur' }
      ]
    },
    {
      prop: 'mobile',
      label: '手机号',
      type: 'input',
      rules: [
        { validator: (rule, value, callback) => validatemobile({...rule, isEdit}, value, callback), trigger: 'blur' }
      ]
    },
    {
      prop: 'sex',
      label: '性别',
      type: 'radio',
      options: [
        { label: '男', value: 1 },
        { label: '女', value: 2 }
      ]
    },
    {
      prop: 'status',
      label: '状态',
      type: 'switch',
      activeText: '启用',
      inactiveText: '禁用',
      activeValue: 0,
      inactiveValue: 1
    }
  ]
}

// 表格列配置
export const getTableColumns = (): TableColumn[] => [
  {
    prop: 'id',
    label: 'ID',
    width: 80,
    sortable: true
  },
  {
    prop: 'username',
    label: '用户名',
    width: 120,
    sortable: true
  },
  {
    prop: 'nickname',
    label: '昵称',
    width: 120
  },
  {
    prop: 'email',
    label: '邮箱',
    width: 200
  },
  {
    prop: 'mobile',
    label: '手机号',
    width: 130
  },
  {
    prop: 'sex',
    label: '性别',
    width: 80,
    formatter: (row: any) => {
      const sexMap: Record<number, string> = {
        1: '男',
        2: '女'
      }
      return sexMap[row.sex] || '未知'
    }
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    formatter: (row: any) => {
      return row.status === 1 ? '启用' : '禁用'
    }
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: 180,
    sortable: true,
  },
  {
    prop: 'updateTime',
    label: '更新时间',
    width: 180,
    sortable: true
  }
]

// 表格搜索字段配置
export const getSearchFields = (): SearchField[] => [
  {
    key: 'username',
    label: '用户名',
    type: 'text'
  },
  {
    key: 'email',
    label: '邮箱',
    type: 'text'
  },
  {
    key: 'mobile',
    label: '手机号',
    type: 'text'
  },
  {
    key: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  },
  {
    key: 'sex',
    label: '性别',
    type: 'select',
    options: [
      { label: '男', value: 1 },
      { label: '女', value: 2 }
    ]
  },
    {
      key: 'createTime',
      label: '创建时间',
      type: 'date'
    },
]

// 表格配置
export const getTableConfig = (): TableConfig => ({
  title: '用户管理测试页面',
  description: '这是一个使用通用表格组件的测试页面',
  showHeader: true,
  showSearch: true,
  showPagination: true,
  showSelection: true,
  showIndex: true,
  showActions: true,
  showAddButton: true, // 使用自定义操作按钮
  addButtonText: '添加用户',
  showEditButton: true, // 使用自定义操作列
  showDeleteButton: true, // 使用自定义操作列
  stripe: true,
  border: true,
  actionWidth: 200,
  actionFixed: 'right',
  pageSizes: [10, 20, 50, 100],
  paginationLayout: 'total, sizes, prev, pager, next, jumper',
  searchFields: getSearchFields()
})

// API配置
export const getApiConfig = (): ApiConfig => ({
  listApi: getUserPage,
  deleteApi: deleteUser
})

// 业务操作API
export const TableApis = {
  createUser,
  updateUser,
  deleteUser,
}